package com.starblink.search.category.ui.list

import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.activity.BaseTVMLoadingActivity
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.extraOf
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.basic.ext.screenWidth
import com.starblink.basic.route.RoutePage
import com.starblink.search.category.data.CategoryLevelEnum
import com.starblink.search.category.data.CategoryModel
import com.starblink.search.category.ui.list.cell.LeveThreeCell
import com.starblink.search.category.ui.list.cell.LevelOneCell
import com.starblink.search.category.ui.list.cell.LevelTwoCell
import com.starblink.search.databinding.ActivityCategoryListBinding
import com.starblink.search.databinding.CellLevelOneBinding
import com.starblink.search.databinding.CellLevelThreeBinding
import com.starblink.search.databinding.CellLevelTwoBinding


/**
 * 商品类目列表
 */
//@Route(path = RoutePage.Search.PAGE_GOODS_CATEGORY)
internal class CategoryListActivity :
    BaseTVMLoadingActivity<ActivityCategoryListBinding, ListVM>() {

    @JvmField
    @Autowired(name = RoutePage.ARG.ID)
    var categoryId: String? = null

    private val adapter by lazyOnNone {
        object : MutableAdapter(viewModel.contentList) {
            override fun getItemViewType(position: Int): Int {
                return viewModel.contentList[position].source.level ?: 0
            }
        }.apply {
            addVhDelegate {
                LevelOneCell(CellLevelOneBinding.inflate(layoutInflater, it, false)) { model, pos ->
                    clickLevelOne(model)
                }
            }
            addVhDelegates(
                {
                    LevelTwoCell(
                        CellLevelTwoBinding.inflate(
                            layoutInflater,
                            it,
                            false
                        )
                    ) { model, pos ->
                        clickLevelOne(model)
                    }
                },
                {
                    LeveThreeCell(CellLevelThreeBinding.inflate(layoutInflater, it, false))
                },
            ) { model, position ->
                val res = model.source.level ?: 0
                res
            }
//            addVhDelegate {
//                LeveThreeCell(CellLevelThreeBinding.inflate(layoutInflater, it, false))
//            }
        }
    }

    override fun initViewBinding(): ActivityCategoryListBinding =
        ActivityCategoryListBinding.inflate(layoutInflater)

    override fun initData() {
        viewModel.initCategoryId = categoryId
        super.initData()
    }

    override fun initLoad() {
        super.initLoad()
        viewModel.loadInitData()

    }

    override fun initView() {
        super.initView()
        viewBinding.titleBar.leftView.setOnClickListener {
            popSelf()
        }
        viewBinding.titleBar.rightView.setOnClickListener {
            navigationTo(RoutePage.Search.PAGE_SEARCH) {
                extraOf(RoutePage.Search.ARG_SCENE to RoutePage.Search.SCENE.GOODS.value)
            }
        }

        viewBinding.recycler.layoutManager = LinearLayoutManager(this)
        viewBinding.recycler.adapter = adapter
//        viewBinding.recycler.itemAnimator = null

    }

    override fun initObservable() {
        super.initObservable()
        viewModel.liveData.observe(this) {
            adapter.refreshAll()
            viewBinding.empty.visibleOrGone(it.isEmpty())
            if (viewModel.initCategoryId?.isNotEmpty() == true
                && viewModel.initExpandModel != null
                && viewModel.initExpandIndex != null
            ) {
                viewBinding.recycler.postDelayed({
                    scrollVisibleTop(viewModel.initExpandIndex!!, viewModel.initExpandModel!!)
                }, 0)
            }
        }
    }

    private fun clickLevelOne(model: CategoryModel) {
        model.source.id ?: return

        val position = viewModel.contentList.indexOfFirst { it == model }
        if (position < 0) {
            return
        }
        if (model.children == null) {
            viewModel.queryChildren(model.source.id.toString()) { it ->
                model.children = it
                it.takeIf { it?.isNotEmpty() == true }?.let {
                    viewModel.contentList.addAll(position + 1, it)
                    adapter.notifyItemRangeInserted(position + 1, it.size)
                    if ((model.source.level ?: 0) > CategoryLevelEnum.ONE.level) {
                        adapter.notifyItemChanged(position)
                    }
                }
                model.expand = !model.expand

                scrollVisibleTop(position, model)
            }
            return
        }
        val children = model.children!!
        if (model.expand) {
            var count = 0
            val iterator = viewModel.contentList.iterator()
            var index = 0
            while (iterator.hasNext()) {
                var item = iterator.next()
                if (index++ < position) {
                    continue
                }
                if (children.contains(item)) {
                    iterator.remove()
                    count++
                    val children2 = item.children
                    if (item.expand && children2?.isNotEmpty() == true && iterator.hasNext()) {
                        item.expand = false
                        children2.forEach {
                            if (iterator.hasNext()) {
                                item = iterator.next()
                                if (it == item) {
                                    it.expand = false
                                    iterator.remove()
                                    count++
                                }
                            }
                        }
                    }
                }
            }
            if (count > 0) {
                adapter.notifyItemRangeRemoved(position + 1, count)
            }
        } else {
            viewModel.contentList.addAll(position + 1, children)
            adapter.notifyItemRangeInserted(position + 1, children.size)
        }
        model.expand = !model.expand

        if ((model.source.level ?: 0) > CategoryLevelEnum.ONE.level) {
            adapter.notifyItemChanged(position)
        }

        scrollVisibleTop(position, model)
    }

    private fun scrollVisibleTop(position: Int, model: CategoryModel) {
        if (!model.expand) return
        viewBinding.recycler.postDelayed({
            if (model.source.level == CategoryLevelEnum.ONE.level) {
                if (position == 0) return@postDelayed

                val cell = viewBinding.recycler.findViewHolderForLayoutPosition(position)
                val scrolled = if (cell != null) {
                    val location = intArrayOf(0, 0)
                    cell.itemView.getLocationInWindow(location)
                    location[1] - viewBinding.titleBar.measuredHeight
                } else {
                    position * ((screenWidth - viewBinding.recycler.paddingLeft - viewBinding.recycler.paddingRight) * (140.0 / 343.0) + 12.dp2px())
                }
                viewBinding.recycler.smoothScrollBy(0, scrolled.toInt())
            } else if (model.source.level == CategoryLevelEnum.TWO.level) {
                viewBinding.recycler.smoothScrollToPosition(position + (model.children?.size ?: 0))
            }
        }, 500)
    }

}